//
//  RdbScreenLaunchController.swift
//  rdb-led-banner
//
//  Created by radiobox3 on 2025/4/17.
//

import UIKit
import SnapKit
import Lottie
import Alamofire

class RdbScreenLaunchController: BaseViewController {
    
    var completion: (() -> Void)?
    
    var isNetworking: Bool = false{
        didSet{
            self.loadingView.isHidden = !isNetworking
            self.launchImageView.isHidden = !isNetworking
            self.networkingDesLabel.isHidden = isNetworking
            self.networkStatusLabel.isHidden = isNetworking
            self.networkStatusLabel.isHidden = isNetworking
            self.networkSettingBtn.isHidden = isNetworking
            self.launchNoNetworkImageView.image = UIImage(named: isNetworking ? "launch_mask" : "launch_mask_network")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(backgroundImageView)
        self.backgroundImageView.snp.makeConstraints{
            $0.edges.equalToSuperview()
        }
        self.view.addSubview(launchNoNetworkImageView)
        self.launchNoNetworkImageView.snp.makeConstraints{
            $0.top.equalTo(178)
            $0.centerX.equalToSuperview()
            $0.size.equalTo(CGSize(width: 326, height: 208))
        }
        self.view.addSubview(launchImageView)
        self.launchImageView.snp.makeConstraints{
            $0.top.centerX.size.equalTo(launchNoNetworkImageView)
        }

        self.view.addSubview(networkSettingBtn)
        self.networkSettingBtn.snp.makeConstraints{
            $0.centerX.equalToSuperview()
            $0.bottom.equalTo(-UIDevice.safeAreaBottom() - 33)
            $0.size.equalTo(CGSize(width: UIDevice.contentWidth(), height: 54))
        }
        self.view.addSubview(networkingDesLabel)
        self.networkingDesLabel.snp.makeConstraints{
            $0.centerX.equalToSuperview()
            $0.bottom.equalTo(networkSettingBtn.snp.top).offset(-20)
            $0.width.lessThanOrEqualTo(UIDevice.screenWidth() - 32)
        }
        self.view.addSubview(networkStatusLabel)
        self.networkStatusLabel.snp.makeConstraints{
            $0.centerX.equalToSuperview()
            $0.bottom.equalTo(networkingDesLabel.snp.top).offset(-20)
        }
        self.view.addSubview(loadingView)
        self.loadingView.snp.makeConstraints{
            $0.bottom.equalTo(-UIDevice.safeAreaBottom()-32)
            $0.size.equalTo(CGSize(width: UIDevice.contentWidth(), height: 95))
            $0.centerX.equalToSuperview()
        }
        self.isNetworking = false
        self.networkingAuthorization()
    }
    
    func networkingAuthorization(){
        if NetworkReachabilityManager.default?.isReachable == true {
            self.startLoading()
        }else{
            NetworkReachabilityManager.default?.startListening(onUpdatePerforming: {[weak self] status in
                if status == .reachable(.cellular) || status == .reachable(.ethernetOrWiFi) {
                    DispatchQueue.main.async {
                        self?.startLoading()
                    }
                }
            })
        }
    }
    
    func startLoading(){
        self.isNetworking = true
        /// 拉取商品信息+验证交易数据
        RdbSubscribeProductRequest.shared.requestProduct(nil)
        if RdbSubscribeReceiptRequest.shared.getReceiptBase64String() == nil{
            RdbSubscribeReceiptRequest.shared.refreshReceipt{ _,_ in
                RdbSubscribeManager.shared.verifyReceipt()
            }
        }else{
            RdbSubscribeManager.shared.verifyReceipt()
        }
        //加载 lotties 动画
        let animation = LottieAnimation.named("launch")
        self.launchImageView.animation = animation
        self.launchImageView.play(fromProgress: 0, toProgress: 1, loopMode: .playOnce)
        //开启定时任务
        self.loadingView.startLoading()
    }
    
    private lazy var backgroundImageView: UIImageView = {
        let backgroundImageView = UIImageView(image: UIImage(named: "launch_background"))
        backgroundImageView.contentMode = .scaleAspectFill
        return backgroundImageView
    }()
    private lazy var launchNoNetworkImageView: UIImageView = {
        let launchNoNetworkImageView = UIImageView(image: UIImage(named: "launch_mask_network"))
        return launchNoNetworkImageView
    }()
    private lazy var launchImageView: LottieAnimationView = {
        let launchImageView = LottieAnimationView()
        return launchImageView
    }()
    
    private lazy var networkSettingBtn: UIButton = {
        let button = UIButton(type: .system)
        button.layer.cornerRadius = 27
        button.clipsToBounds = true
        button.titleLabel?.font = UIFont.semibold(20)
        button.setTitle("setting_network".localized, for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = UIColor("#5210E1")
        button.addTarget(self, action: #selector(openNetworkSettingAction), for: .touchUpInside)
        return button
    }()
    private lazy var networkingDesLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white.withAlphaComponent(0.6)
        label.textAlignment = .center
        label.numberOfLines = 0
        label.font = UIFont.regular(14)
        label.text = "check_network".localized
        return label
    }()
    private lazy var networkStatusLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white
        label.textAlignment = .center
        label.numberOfLines = 0
        label.font = UIFont.semibold(18)
        label.text = "badnetworking".localized
        return label
    }()
    private lazy var loadingView: LoadingView = {
        let loadingView = LoadingView(type: .LOADING)
        loadingView.completion = { [weak self] in
            guard let self = self else { return }
            self.completion?()
        }
        return loadingView
    }()
    
    @objc func openNetworkSettingAction(){
        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
            return
        }
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
        }
    }
}
